/**
 * Created by sunny.w <iwisunny@gmail.com> on 16-2-16.
 */

/**
 * user index
 */
$(function(){
    $('.btn_edit').on('click',function(){
        var id=$(this).parents('tr').find('td:first').text();
        redirect('/user/edit/'+id);
    });

    $('.btn_del').on('click', function(){
        var that=$(this);
        var eid=$(this).data('eid');

        wxi.ui.modal({
            title: '删除用户',
            msg: '确认删除该用户吗?',
            height:80,
            cb: function(){
                var modal=arguments[1] || null;
                $.get('/user/delete',{user_id: eid}, function(d){
                    if(d.success){
                        wxi.util.tipMsg('','删除成功', 800, function(){
                            modal && modal.hide();
                            $('body').removeClass('modal-open');

                            that.parents('tr').remove();
                        });
                    }
                    else{
                        wxi.util.tipMsg('','删除失败');
                        return false;
                    }
                },'json');
            }

        });



    });
});

/**
 * user add
 */
$(function(){
    var btn_reg = $('#btn-reg-user');
    var fm = $('.wrap-monitor > form');

    btn_reg.on('click', function () {
        var fm_data=wxi.util.preCheckForm(fm);

        if(fm_data.username=='' || fm_data.password==''){
            wxi.util.tipMsg('','请填写用户名与密码');
            return false;
        }

        if(fm_data.username.length <5 || fm_data.password.length <5){
            wxi.util.tipMsg('','用户名或密码长度不小于5', 1000);
            return false;
        }

        if(fm_data.password !== fm_data.repeat_pwd){
            wxi.util.tipMsg('', '密码前后输入不一致');
            return false;
        }

        delete fm_data.repeat_pwd;
        console.log(fm_data);

        var op=fm_data['id']=='' ? '添加' : '修改';

        var is_reset_pwd=false, ajax_url='/user/add';
        if(location.href.indexOf('/reset_pwd') !== -1){
            ajax_url='/user/reset_pwd';
            is_reset_pwd=true;
        }

        $.post(ajax_url, {entity: fm_data}, function(d){
            if(d.success){
                var tip_msg=is_reset_pwd? '密码修改成功' : op+'成功, 跳转到用户列表...';
                wxi.util.tipMsg('', tip_msg, 800, function(){
                    if(is_reset_pwd){
                        location.href='/';
                    }
                    else{
                        location.href='/user';
                    }
                });
            }
            else{
                wxi.util.tipMsg('',d.info);
            }

        }, 'json');

        return false;

    });

});